package com.itchen.controller;

import com.github.pagehelper.PageInfo;
import com.itchen.common.DataResult;
import com.itchen.emtity.dataobject.UploadDO;
import com.itchen.emtity.vo.UploadVO;
import com.itchen.service.FileUploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

@RestController
public class FileController {

    @Autowired
    private FileUploadService fileUploadService;

    /**
     * 文件上传
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/chen/upload")
    public DataResult<String> uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        fileUploadService.uploadFile(file);
        return DataResult.success("上传成功");
    }

    /**
     * 获取文件列表
     * @return
     */
    @GetMapping("/chen/uploads")
    public DataResult<PageInfo<UploadDO>> uploadFileList(@RequestParam(value = "page", defaultValue = "0", required = false) Integer page,
                                                         @RequestParam(value = "limit",defaultValue = "5", required = false) Integer limit,
                                                         @RequestParam("orName") String orName) {
        PageInfo<UploadDO> pageInfo = fileUploadService.getUploadFileList(page,limit,orName);
        return DataResult.success(pageInfo);
    }

    /**
     * 删除上传文件数据
     * @param uploadId
     * @return
     */
    @DeleteMapping("/chen/upload/{uploadId}")
    public DataResult<String> deleteUploadFilesData(@PathVariable("uploadId") String uploadId){
        fileUploadService.deleteUploadFileDataById(uploadId);
        return DataResult.success("删除成功");
    }

    /**
     * 批量删除上传文件数据
     * @return
     */
    @DeleteMapping("/chen/uploads")
    public DataResult<String> deletesUploadFilesData(@RequestBody List<UploadVO> uploadVOS){
        fileUploadService.deleteUploadFileDataByIds(uploadVOS);
        return DataResult.success("删除成功");
    }

    /**
     * 下载文件
     * @return
     */
    @GetMapping("/chen/downloads/{uploadId}")
    public void downloadUploadFilesData(@PathVariable("uploadId") String uploadId,
                                        HttpServletResponse response,
                                        String sign){
        fileUploadService.downloadUploadFilesData(uploadId, sign, response);
    }

}
